package com.yimi.yinhepda.views.dispatch_module;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.DispatchTaskAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.CarPlateTableDao;
import com.yimi.yinhepda.db.dao.DispactchScanTableDao;
import com.pda.ym.db.table.CarPlateTable;
import com.pda.ym.utils.ProvinceEnum;
import com.yimi.yinhepda.entity.response.DispatchTaskResponse;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.CarNoSelectDialog;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.base.BaseInitActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;

/**
 * 集中派送任务列表
 *
 * @author tianjin
 */
public class DispatchTaskActivity extends BaseInitActivity {

    /**
     * 标题栏左边
     */
    @Bind(R.id.title)
    TextView mTvTitle;
    /**
     * 标题栏中间
     */
    @Bind(R.id.num)
    TextView mTvNum;
    /**
     * 省市车牌按钮
     */
    @Bind(R.id.btn_carPlate)
    Button btnPlateNo;
    /**
     * 车牌号输入框
     */
    @Bind(R.id.et_carNo)
    EditText etCarNo;
    /**
     * 下拉数据按钮
     */
    @Bind(R.id.btn_down)
    Button btnDownload;
    /**
     * 配送列表
     */
    @Bind(R.id.dispatch_task_listview)
    ListView mListView;
    private List<DispatchTaskResponse.DispatchTaskEntity> mDataList = new ArrayList<>();
    private DispatchTaskAdapter mAdapter;
    private DispactchScanTableDao mDispactchScanTableDao;
    /**
     * 配送任务实体
     */
    public static DispatchTaskResponse.DispatchTaskEntity mDispatchTaskEntity;
    /**
     * 总的未上传数量
     */
    private int totalNotUploadNum;
    /**
     * 临时转换的车牌号
     */
    private String mTempCarNo = "";

    public DispatchTaskActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return getString(R.string.page_dispatch_task);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_dispatch_task;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mTvTitle.setText("配送任务列表");
    }

    @Override
    public void initEvent() {
        findViewById(R.id.dispatch_task_back).setOnClickListener(this);
        findViewById(R.id.dispatch_task_execute).setOnClickListener(this);
        btnPlateNo.setOnClickListener(this);
        btnDownload.setOnClickListener(this);
        etCarNo.addTextChangedListener(new AddTextChange());
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        mDispactchScanTableDao = new DispactchScanTableDao();
        //设置车牌
        List<CarPlateTable> carPlateTables = new CarPlateTableDao().getAllData();
        if (carPlateTables != null) {
            if (carPlateTables.size() > 0) {
                btnPlateNo.setText(carPlateTables.get(0).getCarPlate());
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //查询未上传数据
        totalNotUploadNum = mDispactchScanTableDao.queryNotUploadDataNum();
        mTvNum.setText(totalNotUploadNum + "");
        loadData();
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            if (result.contains(Common.SP_C_)) {
                btnPlateNo.setText(ProvinceEnum.getByCode(result.split(Common.SP_C_)[0]).getName());
                etCarNo.setText(result.split(Common.SP_C_)[1]);
            }
        }
    }

    public void loadData() {
        String carNo = etCarNo.getText().toString();
        if ("".equals(carNo)) {
            showToast("请先输入车牌号！");
            return;
        }
        showPgDlg("正在加载...");
        Map param = new HashMap(4);
        param.put("carNo", btnPlateNo.getText().toString() + carNo);
        param.put("distrDeptCode", SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE));
        //预约开始时间（String）（格式：yyyy-MM-ddTHH:mm:ssZ）格林威治开始时间
//        param.put("subscribeBeginTime", DateHelper.getDateFormate(DateHelper.getOldDate(-1)) + "T16:00:00.000Z");
        //预约结束时间（String）（格式：yyyy-MM-ddTHH:mm:ssZ）格林威治结束时间
//        param.put("subscribeEndTime", DateHelper.getDateFormate(new Date()) + "T15:59:59.084Z");
        new NetRequest().setUrl(Constants.URL_QUERY_TASK_AND_DETAIL)
                .setMethod(NetRequest.Method.GET)
                .setParams(param)
                .setResponsClazz(DispatchTaskResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        if (msg != null) {
                            showToast(msg);
                        } else {
                            showToast("服务器出错了!");
                        }
                        dismissPgDlg();
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        DispatchTaskResponse response = (DispatchTaskResponse) obj;
                        showDataDetail(response);
                        dismissPgDlg();
                    }
                });
    }

    /**
     * 数据在列表中展示等
     */
    private void showDataDetail(DispatchTaskResponse response) {
        mDataList = response.getData();
        Iterator<DispatchTaskResponse.DispatchTaskEntity> it = mDataList.iterator();
        while (it.hasNext()) {
            DispatchTaskResponse.DispatchTaskEntity entity = it.next();
            if (entity.getTaskState() == 3 || entity.getIsDelete() == 1) {
                it.remove();
            }
        }
        mAdapter = new DispatchTaskAdapter(this, mDataList);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.dispatch_task_back:
                finish();
                break;
            case R.id.btn_carPlate:
                //省市车牌按钮
                CarNoSelectDialog.showCarPlateDialog(this, new CarNoSelectDialog.CarNoSelectListener() {
                    @Override
                    public void onclick(String carPlate) {
                        btnPlateNo.setText(carPlate);
                    }
                });
                break;
            case R.id.btn_down:
                //下拉数据按钮
                loadData();
                break;
            case R.id.dispatch_task_execute:
                if (mAdapter == null) {
                    showToast("暂时没有数据!");
                    return;
                }
                int i = mAdapter.getCurrentPosition();
                if (i != -1) {
                    mDispatchTaskEntity = mDataList.get(i);
                    Intent intent = new Intent(DispatchTaskActivity.this, DispatchScanActivity.class);
                    startActivity(intent);
                } else {
                    showToast("请选择一项任务执行!");
                }
                break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(CountEvent countEvent) {
        mTvNum.setText(countEvent.getCount() + "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private class AddTextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            //车牌号英文字母转换成大写
            String carNo = etCarNo.getText().toString().toUpperCase();
            if (!carNo.equalsIgnoreCase(mTempCarNo) && !"".equals(carNo)) {
                mTempCarNo = carNo;
                etCarNo.setText(carNo);
                etCarNo.setSelection(carNo.length());
                if (carNo.length() >= 6) {
                    loadData();
                }
            }
        }
    }
}